package com.sunseen.intelligencebus.user

import android.os.Bundle
import android.widget.TextView
import androidx.databinding.ViewDataBinding
import com.avos.avoscloud.AVException
import com.avos.avoscloud.AVQuery
import com.avos.avoscloud.AVUser
import com.avos.avoscloud.GetCallback
import com.sunseen.intelligencebus.R
import com.sunseen.intelligencebus.base.AbsBindingFragment
import com.sunseen.intelligencebus.databinding.FragmentUserBinding
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode


class UserFragment : AbsBindingFragment() {

    companion object {
        fun newInstance(): UserFragment {
            return UserFragment()
        }
    }

    override fun setLayout(): Int {
        return R.layout.fragment_user
    }

    lateinit var balanceValueTv: TextView
    lateinit var name: String
    var balance: Double = 0.00

    override fun onBindView(viewDataBinding: ViewDataBinding,bundle: Bundle?) {
        EventBus.getDefault().register(this)
        name = AVUser.getCurrentUser().username
        val binding = viewDataBinding as FragmentUserBinding
        binding.userNameTv.text = name
        balanceValueTv = binding.balanceValueTv
        val query: AVQuery<Account> = AVQuery.getQuery(Account::class.java)
        query.whereEqualTo("name", name)
        query.getFirstInBackground(object : GetCallback<Account>() {
            override fun done(p0: Account?, p1: AVException?) {
                if (p0 != null) {
                    balance = p0.blance
                }
                balanceValueTv.text = balance.toString()
            }
        })
        binding.topUpBtn.setOnClickListener {
            getParentDelegate<AbsBindingFragment>().start(TopUpFragment())
        }
    }

    override fun onDestroyView() {
        super.onDestroyView()
        EventBus.getDefault().unregister(this)
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onBalanceUpdate(update: BalanceUpdateEvent) {
        balance = update.newValue
        balanceValueTv.text = balance.toString()
    }
}
